﻿using DotNetty.Buffers;
using DotNetty.Codecs.Http.WebSockets;
using DotNetty.Handlers.Flow;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsApp1.common;

namespace WinFormsApp1.dotnetty
{
    internal class SocketDotNettyHandler : ChannelHandlerAdapter
    {
        
        public override void ChannelRead(IChannelHandlerContext ctx, object message)
        {
            //IByteBuffer message = msg as IByteBuffer;
            //string utfmsg = message.ToString(Encoding.UTF8);
            Form1.form.SetTextBoxValue(DateTime.Now.ToString()+"-"+ctx.Channel.RemoteAddress + "收到信息：" + message);
            
            ctx.WriteAndFlushAsync("服务器返回："+message);

            Dictionary<object, IChannelHandlerContext> diclist = WebSocketGroup.ConnChannelList;
            for (int i = 0; i < diclist.Count; i++)
            {
                (object key, IChannelHandlerContext ch) = diclist.ElementAt(i);
                //Console.WriteLine($"key={key},value={diclist[key]}");
                ch.WriteAndFlushAsync(new TextWebSocketFrame("服务器返回：" + ctx.Channel.RemoteAddress +  message));
            }
        }

        public override void HandlerAdded(IChannelHandlerContext ctx)
        {
            Form1.form.SetTextBoxValue(ctx.Channel.RemoteAddress + " 上线" );
            Console.WriteLine($"Client {ctx} is Connected!");
            Form1.form.SetListValue(ctx.Channel.RemoteAddress.ToString(),true);
            SocketGroup.ConnChannelList.Add(ctx.Channel.Id.AsLongText, ctx);
            base.HandlerAdded(ctx);
        }

        public override void HandlerRemoved(IChannelHandlerContext ctx)
        {
            Form1.form.SetTextBoxValue(ctx.Channel.RemoteAddress + " 离线");
            Console.WriteLine($"Client {ctx} is Disconnected!");
            Form1.form.SetListValue(ctx.Channel.RemoteAddress.ToString(),false);
            SocketGroup.ConnChannelList.Remove(ctx.Channel.Id.AsLongText);
            base.HandlerRemoved(ctx);
        }

        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            if (evt is IdleStateEvent eventState)
            {
                switch (eventState.State)
                {
                    case IdleState.WriterIdle:

                        break;
                    case IdleState.ReaderIdle:

                        break;
                    case IdleState.AllIdle:

                        break;
                }
            }
        }
    }
}
